package org.abio.XasML.rpc
{
	import flash.events.Event;
	
	import mx.rpc.IResponder;
	import mx.rpc.Responder;

	public class Command
	{
		private var delayedCall:Function=null;
		private var responder:IResponder=null;

		public function Command(delayedCall:Object, resultHandler:Function, faultHandler:Function=null)
		{
			if(delayedCall is Function){
				this.delayedCall=delayedCall as Function;
			}else if(delayedCall.hasOwnProperty('send')){					//delayedCall is AbstractInvoker
				this.delayedCall=delayedCall.send;
			}
			this.responder=new Responder(function result(data:Object):void{
				if(resultHandler!=null){
					if(data is Event){	resultHandler(data.result);}
					else{	resultHandler(data);}
				}
			}, function fault(info:Object):void{
				if(faultHandler!=null){
					if(info is Event){	faultHandler(info.fault);}
					else{	faultHandler(info);}	
				}			
			});
		}

		public function execute(...args):Object{
			var result:Object=this.delayedCall.apply(null, args);			//result is AsyncToken
			result.addResponder(this.responder);
			return result;
		}
	}
}